package com.hanzidong.cms.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.hanzidong.cms.entity.Article;
import com.hanzidong.cms.entity.Category;
import com.hanzidong.cms.entity.Channel;
import com.hanzidong.cms.entity.Slide;
import com.hanzidong.cms.service.ArticleService;
import com.hanzidong.cms.service.ChannelService;
import com.hanzidong.cms.service.SlideService;
import com.hanzidong.util.DateUtil;

@Controller
public class IndexController {
	
	@Resource
	private ArticleService articleService;
	
	@Resource
	private ChannelService channelService;
	
	@Resource
	private SlideService slideService;
	
	
	@RequestMapping(value = {"","/","index"})
	public String index(Model m, Article article,
			@RequestParam(defaultValue = "1")Integer pageNum,
			@RequestParam(defaultValue = "3")Integer pageSize) {
		
		//查询左侧导航菜单
		List<Channel> channels = channelService.getChannels();
		m.addAttribute("channels", channels);
		
		//如果是热点数据
		if(article.getChannelId() == null) {
			article.setHot(1);
			
			//查询所有轮播图
			List<Slide> slides = slideService.getSlides();
			
			m.addAttribute("slides", slides);
		}else {
			//如果点击了频道栏目，查询该栏目下所有的分类
			List<Category> categories = channelService.getCategoriesByChannelId(article.getChannelId());
			
			m.addAttribute("categories", categories);
		}
		
		//查询热点或者栏目分类数据
		PageInfo<Article> info = articleService.list(pageNum, pageSize, article);
		m.addAttribute("info", info);
		
		//查询点击量排行榜
		//封装查询数据，必须是已经审核通过的数据
		Article a = new Article();
		a.setStatus(1);
		
		PageInfo<Article> hitInfo = articleService.listByHit(1, 10, a);
		m.addAttribute("hitInfo", hitInfo);
		
		//查询24小时热文
		//封装查询数据，必须是已经审核通过的数据
		Article art = new Article();
		art.setStatus(1);//已审核
		art.setCreated(DateUtil.offsetDate(-1));//设置前一天的时间
		
		PageInfo<Article> hot24Info = articleService.list(1, 10, art);
		m.addAttribute("hot24Info", hot24Info);
		
		
		//将条件返回
		m.addAttribute("article", article);
		
		return "index/index";
	}

	/**
	 * 根据id查询文章详情
	 * @param m
	 * @param id
	 * @return
	 */
	@RequestMapping("articleDetail")
	public String articleDetail(Model m,Integer id) {
		
		//根据id查询文章数据
		Article article = articleService.getArticleById(id);
		
		//将文章数据返回为jsp
		m.addAttribute("article", article);
		
		return "index/detail";
	}
}
